package com.shop.trade.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.shop.common.entity.item.ItemDetails;
import com.shop.common.entity.trade.OrderBase;
import com.shop.common.entity.trade.OrderDetail;
import com.shop.common.entity.user.UserBase;
import com.shop.common.model.ServiceBean;
import com.shop.common.model.param.item.ItemBaseInput;
import com.shop.common.model.param.item.ItemDetailsInput;
import com.shop.common.model.param.trade.*;
import com.shop.common.model.param.user.MessageInput;
import com.shop.common.model.param.user.UserPayInput;
import com.shop.common.model.param.user.UserPayLogInput;
import com.shop.common.model.result.item.ItemBaseOutput;
import com.shop.common.model.result.item.ItemDetailsOutput;
import com.shop.common.model.result.trade.OrderBaseOutput;
import com.shop.common.model.result.trade.OrderDetailOutput;
import com.shop.common.model.result.trade.ShoppingCartOutput;
import com.shop.common.model.result.trade.SnapshotOutput;
import com.shop.common.model.result.user.UserBaseOutput;
import com.shop.common.model.result.user.UserPayOutput;
import com.shop.common.tmpl.BaseService;
import com.shop.common.util.DateUtil;
import com.shop.common.util.SmsContent;
import com.shop.common.util.state.*;
import com.shop.trade.api.service.IOrderSvc;
import com.shop.trade.atom.atomsvc.*;
import com.shop.trade.feign.item.IItemAtomFeignClientSvc;
import com.shop.trade.feign.user.IUserAtomFeignClientSvc;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description:
 *
 * @author zhoulk
 * @date: 2019年04月05日  22:56
 */
@Service
public class OrderSvc extends BaseService implements IOrderSvc {

    @Autowired
    IOrderAtomSvc iOrderAtomSvc;
    @Autowired
    IOrderDetailAtomSvc iOrderDetailAtomSvc;
    @Autowired
    IItemAtomFeignClientSvc iItemAtomFeignClientSvc;
    @Autowired
    IUserAtomFeignClientSvc iUserAtomFeignClientSvc;
    @Autowired
    IShopCartAtomSvc iShopCartAtomSvc;
    @Autowired
    IPayAtomSvc iPayAtomSvc;
    @Autowired
    IOrderCheckAtomSvc iOrderCheckAtomSvc;
    @Autowired
    IOrderLogAtomSvc iOrderLogAtomSvc;
    @Autowired
    ISnapshotAtomSvc iSnapshotAtomSvc;

    @Override
    public ServiceBean<Integer> initOrder(Integer itemId, Integer userId) {
        UserBase userBase = iUserAtomFeignClientSvc.qryUserBaseByUserId(userId);
        if (userBase.getStatus() < UserState.NORMAL.value()) {
            return resultFailed("当前账号状态不能进行交易");
        }
        ItemBaseOutput itemBaseOutput = iItemAtomFeignClientSvc.qryItemBase(itemId);
        if (itemBaseOutput == null || itemBaseOutput.getStatus() != ItemStatus.STATUS_USE.value()) {
            return resultFailed("该商品已失效");
        }

        List<ShoppingCartOutput> list = new ArrayList<>();
        ShoppingCartOutput shoppingCartOutput = new ShoppingCartOutput();
        shoppingCartOutput.setItemId(itemBaseOutput.getItemId());
        shoppingCartOutput.setItemNum(1);
        shoppingCartOutput.setMchtId(itemBaseOutput.getUserId());
        list.add(shoppingCartOutput);
        Map<Integer, ItemBaseOutput> map = new HashMap<>();
        map.put(itemBaseOutput.getItemId(), itemBaseOutput);

        Integer orderId = crateOrder(list, map, userId);
        if (orderId > 0) {
            return resultData(orderId);
        }
        return resultFailed();
    }

    @Override
    public ServiceBean<List<Integer>> initOrderByShopCart(List<Integer> itemIds, Integer userId) {
        UserBase userBase = iUserAtomFeignClientSvc.qryUserBaseByUserId(userId);
        if (userBase.getStatus() < UserState.NORMAL.value()) {
            return resultFailed("当前账号状态不能进行交易");
        }

        ShoppingCartInput shoppingCartInput = new ShoppingCartInput();
        shoppingCartInput.setUserId(userId);
        shoppingCartInput.setItemIds(itemIds);
        ServiceBean<List<ShoppingCartOutput>> serviceBean = iShopCartAtomSvc.selectShoppingCartList(shoppingCartInput);
        if (!serviceBean.isSuccess()) {
            return resultFailed("购买列表中有失效商品");
        }
        List<ShoppingCartOutput> shopCarts = serviceBean.getData();

        //查询商品列表
        ItemBaseInput itemBaseInput = new ItemBaseInput();
        itemBaseInput.setItemIds(itemIds);
        List<ItemBaseOutput> itemBaseOutputList = iItemAtomFeignClientSvc.qryItemBaseList(itemBaseInput);
        ItemDetailsInput itemDetailsInput = new ItemDetailsInput();
        itemDetailsInput.setItemIds(itemIds);
        List<ItemDetailsOutput> itemDetailsOutputList = iItemAtomFeignClientSvc.qryItemDetailsList(itemDetailsInput);

        Map<Integer, ItemBaseOutput> itemBaseOutputMap = new HashMap<>();
        Map<Integer, ItemDetailsOutput> itemDetailsOutputMap = new HashMap<>();
        Map<Integer, List<ShoppingCartOutput>> shopCarMap = new HashMap<>();
        for (ItemBaseOutput itemBase : itemBaseOutputList) {
            itemBaseOutputMap.put(itemBase.getItemId(), itemBase);
        }
        for (ItemDetailsOutput itemDetails : itemDetailsOutputList) {
            itemDetailsOutputMap.put(itemDetails.getItemId(), itemDetails);
        }
        List<String> faildItems = new ArrayList<>();
        List<String> stockItems = new ArrayList<>();
        //按商家进行商品拆分
        for (ShoppingCartOutput shopCart : shopCarts) {
            ItemBaseOutput itemBaseOutput = itemBaseOutputMap.get(shopCart.getItemId());
            if (itemBaseOutput == null || itemBaseOutput.getStatus() != ItemStatus.STATUS_USE.value()) {
                faildItems.add(shopCart.getItemName());
                continue;
            }
            ItemDetails itemDetails = itemDetailsOutputMap.get(shopCart.getItemId());
            if (itemDetails.getStock() < shopCart.getItemNum()) {
                stockItems.add(shopCart.getItemName());
            }
            if (shopCarMap.containsKey(shopCart.getMchtId())) {
                shopCarMap.get(shopCart.getMchtId()).add(shopCart);
            } else {
                List<ShoppingCartOutput> list = new ArrayList<>();
                list.add(shopCart);
                shopCarMap.put(shopCart.getMchtId(), list);
            }
        }
        Map<String, List<String>> tMap = new HashMap<>();
        if (!faildItems.isEmpty()) {
            tMap.put("商品名称：", faildItems);
            return resultFailed("存在失效商品：" + JSON.toJSONString(tMap));
        }
        if (!stockItems.isEmpty()) {
            tMap.put("商品名称：", stockItems);
            return resultFailed("存在库存不足商品：" + JSON.toJSONString(tMap));
        }
        if (shopCarMap.isEmpty()) {
            return resultFailed("商品不存在");
        }
        List<Integer> orderIds = new ArrayList<>();
        Set<Integer> keys = shopCarMap.keySet();
        for (Integer mchtId : keys) {
            Integer orderId = crateOrder(shopCarMap.get(mchtId), itemBaseOutputMap, userId);
            if (orderId > 0) {
                orderIds.add(orderId);
            }
        }
        return resultData(orderIds);
    }

    @Override
    public ServiceBean<BigDecimal> saveOrder(List<OrderBaseInput> orderList, Boolean integral, Integer userId) {
        boolean flag = false;
        Integer payType = 0;
        UserPayOutput userPayOutput = iUserAtomFeignClientSvc.qryUserPayByUserId(userId);
        for (OrderBaseInput orderBaseInput : orderList) {
            ServiceBean<OrderBaseOutput> serviceBean = validateOrder(orderBaseInput.getId(), OrderState.INIT.value());
            if (!serviceBean.isSuccess()) {
                if (serviceBean.getCode().intValue() == 400) {
                    orderBaseInput.setOrderStatus(OrderState.BUYERCANCEL.value());
                    orderBaseInput.setComment(serviceBean.getMsg());
                    iOrderAtomSvc.updateOrderBase(orderBaseInput);
                }
                flag = true;
                continue;
            }

            OrderBaseOutput orderBaseOutput = serviceBean.getData();
            OrderLogInput orderLogInput = new OrderLogInput();//订单日志
            orderLogInput.setOrderId(orderBaseOutput.getId());
            orderLogInput.setBeforProcess(orderBaseOutput.getOrderStatus());

            orderBaseOutput.setComment(orderBaseInput.getComment());
            orderBaseOutput.setAddressId(orderBaseInput.getAddressId());
            orderBaseOutput.setPayType(orderBaseInput.getPayType());
            orderBaseOutput.setTradeType(orderBaseInput.getTradeType());
            if (orderBaseInput.getPayType() == 1) {//当选择线下支付时
                orderBaseOutput.setOrderStatus(OrderState.SUBMIT.value());
                orderLogInput.setAfterProcess(OrderState.SUBMIT.value());
                sendMsg(orderBaseOutput.getMchtId(),"用户下单，订单Id："+orderBaseOutput.getId(),SmsContent.TMPL_1);
            } else {//当线上支付时
                orderBaseOutput.setOrderStatus(OrderState.WAITPAY.value());
                orderLogInput.setAfterProcess(OrderState.WAITPAY.value());
            }
            iOrderAtomSvc.updateOrderBase(orderBaseOutput);//更新订单状态

            orderLogInput.setBuyerId(orderBaseOutput.getBuyerId());
            orderLogInput.setMchtId(orderBaseOutput.getMchtId());
            orderLogInput.setComment("确认订单");
            orderLogInput.setCreateTime(DateUtil.newNowDate());
            orderLogInput.setDataStatus(DataStatus.USE.value());
            orderLogInput.setType(OrderLogType.CONFIRM.value());
            orderLogInput.setState(1);
            iOrderLogAtomSvc.addOrderLog(orderLogInput);//插入订单日志
            payType = orderBaseInput.getPayType();
        }

        if (StringUtils.isBlank(userPayOutput.getPayPwd())) {
            return resultFailed("401");//未设置支付密码
        } else if (StringUtils.isBlank(userPayOutput.getAliPay()) && payType == 2) {
            return resultFailed("402");//未绑定支付宝
        }
        if (flag) {
            return resultFailed("订单状态异常");
        }
        return resultSuccess();
    }

    @Override
    public ServiceBean<OrderBaseOutput> qryOrderById(Integer orderId) {
        OrderBaseInput orderBaseInput = new OrderBaseInput();
        orderBaseInput.setId(orderId);
        ServiceBean<OrderBaseOutput> serviceBean = iOrderAtomSvc.selectOrderBase(orderBaseInput);
        if (serviceBean.isSuccess()) {
            OrderBaseOutput orderBaseOutput = serviceBean.getData();
            OrderDetailInput orderDetailInput = new OrderDetailInput();
            orderDetailInput.setOrderId(orderId);
            List<OrderDetailOutput> orderDetailOutputs = iOrderDetailAtomSvc.selectOrderDetailList(orderDetailInput).getData();
            orderBaseOutput.setOrderDetails(orderDetailOutputs);
        }
        return serviceBean;
    }

    @Override
    public ServiceBean<OrderDetailOutput> qryOrderDtail(OrderDetailInput input) {
        ServiceBean<List<OrderDetailOutput>> serviceBean = iOrderDetailAtomSvc.selectOrderDetailList(input);
        if (serviceBean.isFaild()) {
            return resultFailed();
        }
        OrderDetailOutput orderDetail = serviceBean.getData().get(0);
        SnapshotInput snapshotInput = new SnapshotInput();
        snapshotInput.setOrderId(orderDetail.getOrderId());
        snapshotInput.setItemId(orderDetail.getItemId());
        SnapshotOutput snapshotOutput = iSnapshotAtomSvc.qrySnapshot(snapshotInput).getData();
        orderDetail.setMainImg(snapshotOutput.getMainImg());
        return resultData(orderDetail);
    }

    @Override
    public ServiceBean<List<OrderBaseOutput>> qryOrders(OrderBaseInput orderBaseInput) {
        ServiceBean<List<OrderBaseOutput>> serviceBean = iOrderAtomSvc.selectOrderBaseList(orderBaseInput);
        if (!serviceBean.isSuccess()) {
            return serviceBean;
        }
        List<OrderBaseOutput> orderBaseList = serviceBean.getData();
        for (OrderBaseOutput orderBase : orderBaseList) {
            UserBaseOutput userBaseOutput = iUserAtomFeignClientSvc.qryUserBaseByUserId(orderBase.getMchtId());
            orderBase.setMchtName(userBaseOutput.getNickname());
            OrderDetailInput orderDetailInput = new OrderDetailInput();
            orderDetailInput.setOrderId(orderBase.getId());
            List<OrderDetailOutput> orderDetails = iOrderDetailAtomSvc.selectOrderDetailList(orderDetailInput).getData();
            for (OrderDetailOutput orderDetail : orderDetails) {
                SnapshotInput snapshotInput = new SnapshotInput();
                snapshotInput.setOrderId(orderDetail.getOrderId());
                snapshotInput.setItemId(orderDetail.getItemId());
                SnapshotOutput snapshotOutput = iSnapshotAtomSvc.qrySnapshot(snapshotInput).getData();
                orderDetail.setMainImg(snapshotOutput.getMainImg());
            }
            orderBase.setOrderDetails(orderDetails);
        }
        return serviceBean;
    }

    @Override
    public ServiceBean<Integer> modOrder(OrderBaseInput orderBaseInput) {
        return iOrderAtomSvc.updateOrderBase(orderBaseInput);
    }

    @Override
    public ServiceBean<String> delOrder(Integer orderId, Integer userId) {
        OrderBaseInput orderBaseInput = new OrderBaseInput();
        orderBaseInput.setId(orderId);
        ServiceBean<OrderBaseOutput> serviceBean = iOrderAtomSvc.selectOrderBase(orderBaseInput);
        if (!serviceBean.isSuccess()) {
            return resultFailed("订单不存在或已删除");
        }
        OrderBaseOutput orderBaseOutput = serviceBean.getData();
        if (orderBaseOutput.getBuyerId().intValue() != userId.intValue()) {
            return resultFailed("非法操作（非用户订单）");
        }
        if (orderBaseOutput.getOrderStatus().intValue() != OrderState.BUYERCANCEL.value() &&
                orderBaseOutput.getOrderStatus().intValue() != OrderState.MCHTCANCEL.value() &&
                orderBaseOutput.getOrderStatus().intValue() != OrderState.END.value()) {
            return resultFailed("当前状态订单不能删除");
        }
        return iOrderAtomSvc.deleteOrderBase(orderId);
    }

    @Override
    public ServiceBean cancelOrder(Integer orderId, String reason, Integer userId) {
        OrderBaseInput orderBaseInput = new OrderBaseInput();
        orderBaseInput.setId(orderId);
        ServiceBean<OrderBaseOutput> serviceBean = iOrderAtomSvc.selectOrderBase(orderBaseInput);
        if (!serviceBean.isSuccess()) {
            return resultFailed("订单不存在或已删除");
        }
        OrderBaseOutput orderBaseOutput = serviceBean.getData();
        if (orderBaseOutput.getBuyerId().intValue() != userId.intValue()) {
            return resultFailed("非法操作（非用户订单）");
        }
        if (orderBaseOutput.getOrderStatus().intValue() == OrderState.BUYERCANCEL.value() ||
                orderBaseOutput.getOrderStatus().intValue() == OrderState.MCHTCANCEL.value()) {
            return resultFailed("订单已经取消，请勿重复操作");
        }
        if (orderBaseOutput.getOrderStatus().intValue() >= OrderState.EVALUATE.value()) {
            return resultFailed("订单已完成交易，不能取消");
        }

        OrderLogInput orderLogInput = new OrderLogInput();
        orderLogInput.setOrderId(orderId);
        orderLogInput.setBeforProcess(orderBaseOutput.getOrderStatus());
        orderLogInput.setAfterProcess(OrderState.BUYERCANCEL.value());
        orderLogInput.setBuyerId(orderBaseOutput.getBuyerId());
        orderLogInput.setMchtId(orderBaseOutput.getMchtId());
        orderLogInput.setComment(reason);
        orderLogInput.setCreateTime(DateUtil.newNowDate());
        orderLogInput.setDataStatus(DataStatus.USE.value());

        if (orderBaseOutput.getOrderStatus().intValue() == OrderState.CONFIRM.value() ||
                orderBaseOutput.getOrderStatus().intValue() == OrderState.SHIPMENT.value()) {
            OrderCheckInput orderCheckInput = new OrderCheckInput();
            Date date = DateUtil.newNowDate();
            orderCheckInput.setOrderId(orderId);
            orderCheckInput.setBuyerId(userId);
            orderCheckInput.setMchtId(orderBaseOutput.getMchtId());
            orderCheckInput.setCheckReason(reason);
            orderCheckInput.setCheckType(OrderCheckType.CANCEL.value());
            orderCheckInput.setState(OrderCheckState.WAITCHECK.value());
            orderCheckInput.setCreateTime(DateUtil.newNowDate());
            orderCheckInput.setLastCheckTime(DateUtil.afterDate(date, 3));
            orderCheckInput.setDataStatus(DataStatus.USE.value());
            iOrderCheckAtomSvc.addOrderCheck(orderCheckInput);

            orderLogInput.setType(OrderLogType.CANCELCHEKING.value());
            orderLogInput.setState(0);
            iOrderLogAtomSvc.addOrderLog(orderLogInput);
            orderBaseInput.setOrderStatus(OrderState.CHECKING.value());
            iOrderAtomSvc.updateOrderBase(orderBaseInput);
            return resultFailed("已提交取消申请，等待卖家审核");
        }
        if (orderBaseOutput.getOrderStatus().intValue() == OrderState.PAID.value()) {
            refund(orderBaseOutput, 1);//退款
        }
        orderLogInput.setType(OrderLogType.CANCEL.value());
        orderLogInput.setState(1);

        iOrderLogAtomSvc.addOrderLog(orderLogInput);
        orderBaseInput.setOrderStatus(OrderState.BUYERCANCEL.value());
        return iOrderAtomSvc.updateOrderBase(orderBaseInput);
    }

    @Override
    public ServiceBean<OrderBaseOutput> validateOrder(Integer orderId, Integer state) {
        ServiceBean<OrderBaseOutput> result = new ServiceBean<>();
        result.setSuccess(false);
        ServiceBean<OrderBaseOutput> serviceBean = iOrderAtomSvc.selectOrderBaseById(orderId);
        if (serviceBean.isFaild()) {
            result.setData(null);
            result.setMsg("订单不存在");
            result.setCode(100);
            return result;
        }
        OrderBaseOutput orderBaseOutput = serviceBean.getData();
        if (orderBaseOutput.getOrderStatus().intValue() != state.intValue()) {
            result.setData(orderBaseOutput);
            result.setMsg("订单状态异常");
            result.setCode(200);
            return result;
        }
        List<OrderDetailOutput> orderDetailOutputs = iOrderDetailAtomSvc.selectOrderDetailByOrderId(orderBaseOutput.getId()).getData();
        for (OrderDetailOutput orderDetailOutput : orderDetailOutputs) {
            ItemBaseOutput itemBaseOutput = iItemAtomFeignClientSvc.qryItemBase(orderDetailOutput.getItemId());
            ItemDetailsOutput itemDetailsOutput = iItemAtomFeignClientSvc.qryItemDetails(orderDetailOutput.getItemId());
            if (itemBaseOutput == null) {
                result.setData(orderBaseOutput);
                result.setMsg("订单存在已失效商品");
                result.setCode(400);
                return result;
            }
            if (itemBaseOutput.getStatus().intValue() != ItemStatus.STATUS_USE.value()) {
                result.setData(orderBaseOutput);
                result.setMsg("订单存在不可售商品");
                result.setCode(400);
                return result;
            }
            if (itemDetailsOutput.getStock() < orderDetailOutput.getBuyNum()) {
                result.setData(orderBaseOutput);
                result.setMsg("订单商品库存不足");
                result.setCode(400);
                return result;
            }
        }
        return resultData(orderBaseOutput);
    }

    @Override
    public ServiceBean<String> checkOrder(Integer id, Integer state, String type, String comment, Integer userId) {
        ServiceBean<OrderBaseOutput> serviceBean = iOrderAtomSvc.selectOrderBaseById(id);
        if (serviceBean.isFaild()) {
            return resultFailed("订单Id错误");
        }
        OrderBaseOutput orderBaseOutput = serviceBean.getData();
        if (orderBaseOutput.getMchtId().intValue() != userId.intValue()) {
            return resultFailed("该订单禁止操作");
        }
        if (orderBaseOutput.getOrderStatus().intValue() != state.intValue()) {
            return resultFailed("订单状态已改变，请刷新页面后重新");
        }
        if (state.intValue() == OrderState.CHECKING.value()) {

        } else if ("pass".equals(type)) {
            OrderBaseInput orderBaseInput = new OrderBaseInput();
            orderBaseInput.setId(orderBaseOutput.getId());
            orderBaseInput.setOrderStatus(OrderState.CONFIRM.value());
            ServiceBean<Integer> modResult = iOrderAtomSvc.updateOrderBase(orderBaseInput);
            if (modResult.isFaild()) {
                return resultFailed("操作失败，请重试");
            }
            OrderLogInput orderLogInput = OrderLogInput.newOrderLogInput(orderBaseOutput.getId(), OrderLogType.MCHTCHECK.value(),
                    1, orderBaseOutput.getOrderStatus(), OrderState.CONFIRM.value(), orderBaseOutput.getBuyerId(),
                    orderBaseOutput.getMchtId(), comment);
            iOrderLogAtomSvc.addOrderLog(orderLogInput);
            sendMsg(orderBaseOutput.getBuyerId(),"订单：+"+orderBaseOutput.getId()+"已审核通过",SmsContent.TMPL_3);
        } else if ("unPass".equals(type)) {
            OrderBaseInput orderBaseInput = new OrderBaseInput();
            orderBaseInput.setId(orderBaseOutput.getId());
            orderBaseInput.setOrderStatus(OrderState.MCHTCANCEL.value());
            ServiceBean<Integer> modResult = iOrderAtomSvc.updateOrderBase(orderBaseInput);
            if (modResult.isFaild()) {
                return resultFailed("操作失败，请重试");
            }
            if (orderBaseOutput.getPayType() == 2) {//在线支付订单，取消时退款到买家账户
                refund(orderBaseOutput, 1008612);
            }
            OrderLogInput orderLogInput = OrderLogInput.newOrderLogInput(orderBaseOutput.getId(), OrderLogType.MCHTCHECK.value(),
                    1, orderBaseOutput.getOrderStatus(), OrderState.MCHTCANCEL.value(), orderBaseOutput.getBuyerId(),
                    orderBaseOutput.getMchtId(), comment);
            iOrderLogAtomSvc.addOrderLog(orderLogInput);
            sendMsg(orderBaseOutput.getBuyerId(),"订单：+"+orderBaseOutput.getId()+"审核不通过",SmsContent.TMPL_4);
        }
        return resultSuccess();
    }

    @Override
    public ServiceBean<String> sendOrder(Integer id, String expresNo) {
        ServiceBean<OrderBaseOutput> serviceBean = iOrderAtomSvc.selectOrderBaseById(id);
        OrderBaseOutput orderBaseOutput = serviceBean.getData();
        if (orderBaseOutput.getOrderStatus().intValue() != OrderState.CONFIRM.value()) {
            return resultFailed("订单状态已改变，请刷新后重试");
        }
        OrderBaseInput orderBaseInput = new OrderBaseInput();
        orderBaseInput.setId(orderBaseOutput.getId());
        orderBaseInput.setOrderStatus(OrderState.SHIPMENT.value());
        if (orderBaseOutput.getTradeType().intValue() == 1) {
            orderBaseInput.setExpressNo(expresNo);
        }
        iOrderAtomSvc.updateOrderBase(orderBaseInput);
        OrderLogInput orderLogInput = OrderLogInput.newOrderLogInput(orderBaseOutput.getId(), OrderLogType.MCHTCHECK.value(),
                1, orderBaseOutput.getOrderStatus(), OrderState.SHIPMENT.value(), orderBaseOutput.getBuyerId(),
                orderBaseOutput.getMchtId(), "卖家已确认发货");
        iOrderLogAtomSvc.addOrderLog(orderLogInput);
        sendMsg(orderBaseOutput.getBuyerId(),"订单："+orderBaseOutput.getId()+"已发货",SmsContent.TMPL_5);
        return resultSuccess();
    }

    @Override
    @Transactional
    public ServiceBean<String> endOrder(OrderBaseInput orderBaseInput) {
        ServiceBean<OrderBaseOutput> serviceBean = iOrderAtomSvc.selectOrderBase(orderBaseInput);
        if (serviceBean.isFaild()) {
            return resultFailed("订单id错误");
        }
        OrderBaseOutput orderBaseOutput = serviceBean.getData();
        if (orderBaseOutput.getOrderStatus() != OrderState.SHIPMENT.value()) {
            return resultFailed("订单状态已发生改变");
        }

        orderBaseInput.setOrderStatus(OrderState.EVALUATE.value());
        iOrderAtomSvc.updateOrderBase(orderBaseInput);
        UserPayOutput userPayOutput = iUserAtomFeignClientSvc.qryUserPayByUserId(orderBaseOutput.getBuyerId());
        UserPayInput userPayInput = new UserPayInput();
        userPayInput.setId(userPayOutput.getId());
        userPayInput.setIntegral(userPayOutput.getIntegral() + orderBaseOutput.getTransPrice().intValue() / 2);
        iUserAtomFeignClientSvc.modUserPay(userPayInput);
        UserPayLogInput userPayLogInput = UserPayLogInput.newUserPayLog(userPayOutput.getUserId(), orderBaseOutput.getTransPrice().intValue() / 2, userPayOutput.getIntegral(), 1, "交易完成赠送积分");
        iUserAtomFeignClientSvc.addUserPayLog(userPayLogInput);
        if (orderBaseOutput.getPayType() == 2) {//在线支付订单确认收货时，将支付金额充值到卖家余额中
            userPayOutput = iUserAtomFeignClientSvc.qryUserPayByUserId(orderBaseOutput.getMchtId());
            userPayInput = new UserPayInput();
            userPayInput.setId(userPayOutput.getId());
            userPayInput.setBalance(orderBaseOutput.getTransPrice().add(orderBaseOutput.getTransPrice()));
            iUserAtomFeignClientSvc.modUserPay(userPayInput);
            userPayLogInput = UserPayLogInput.newUserPayLog(userPayOutput.getUserId(), orderBaseOutput.getTransPrice(), userPayOutput.getBalance(),
                    1, "商品出售成功");
            iUserAtomFeignClientSvc.addUserPayLog(userPayLogInput);
            OrderPayInput orderPayInput = new OrderPayInput();
            orderPayInput.setBuyerId(orderBaseOutput.getMchtId());
            orderPayInput.setMchtId(1008611);
            orderPayInput.setPayType(PayType.TRADE.value());
            orderPayInput.setPayStatus(1);
            orderPayInput.setComment("商品交易成功");
            orderPayInput.setPayPrice(new BigDecimal(0));
            orderPayInput.setBalance(orderBaseOutput.getTransPrice());
            orderPayInput.setPayTime(DateUtil.newNowDate());
            orderPayInput.setCreateTime(DateUtil.newNowDate());
            orderPayInput.setDataStatus(DataStatus.USE.value());
            orderPayInput.setType(1);
            iPayAtomSvc.insertOrderPay(orderPayInput);
        }
        OrderLogInput orderLogInput = OrderLogInput.newOrderLogInput(orderBaseOutput.getId(), OrderLogType.ORDERFINISH.value(),
                1, orderBaseOutput.getOrderStatus(), OrderState.EVALUATE.value(), orderBaseOutput.getBuyerId(),
                orderBaseOutput.getMchtId(), "确认收货");
        iOrderLogAtomSvc.addOrderLog(orderLogInput);
        sendMsg(orderBaseOutput.getMchtId(),"订单："+orderBaseOutput.getId()+" 已收货",SmsContent.TMPL_6);
        return resultSuccess();
    }

    @Override
    public Map<String, Integer> qryOrderItemCount(Integer userId) {
        OrderDetailInput orderDetailInput = new OrderDetailInput();
        orderDetailInput.setBuyerId(userId);
        Integer buy = iOrderDetailAtomSvc.qryOrderDetailCount(orderDetailInput);
        orderDetailInput = new OrderDetailInput();
        orderDetailInput.setMchtId(userId);
        Integer sell = iOrderDetailAtomSvc.qryOrderDetailCount(orderDetailInput);
        Map<String,Integer> map = new HashMap<>();
        map.put("buyNum",buy);
        map.put("sellNum",sell);
        return map;
    }

    /***
     * @Function com.shop.trade.api.service.impl.OrderSvc.crateOrder
     * @Description //TODO 创建订单
     *
     * @param: items
     * @param: itemBaseMap
     * @param: userId
     * @return java.lang.Integer
     * @errorCode //TODO
     *
     * @Author zhoulk
     * @Date 2019/4/14 2:43
     *
     **/
    private Integer crateOrder(List<ShoppingCartOutput> items, Map<Integer, ItemBaseOutput> itemBaseMap, Integer userId) {
        //初始化订单
        OrderBase orderBase = new OrderBase();
        Date now = DateUtil.newNowDate();
        orderBase.setCreateTime(now);
        orderBase.setBuyerId(userId);
        orderBase.setMchtId(items.get(0).getMchtId());
        orderBase.setOrderStatus(OrderState.INIT.value());
        orderBase.setOrderType(1);
        orderBase.setDataStatus(DataStatus.USE.value());
        ServiceBean<Integer> serviceBean = iOrderAtomSvc.insertOrderBase(orderBase);

        //初始化订单商品
        BigDecimal orderPrice = new BigDecimal(0);//订单原价
        BigDecimal transPrice = new BigDecimal(0);//订单优惠后价格
        BigDecimal postage = new BigDecimal(0);//订单邮费

        List<OrderDetail> orderDetails = new ArrayList<>();//订单商品列表
        List<Integer> shopCartIds = new ArrayList<>();
        if (serviceBean.isSuccess()) {
            Integer orderId = serviceBean.getData();
            for (ShoppingCartOutput item : items) {
                ItemBaseOutput itemBaseOutput = itemBaseMap.get(item.getItemId());
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(orderId);
                orderDetail.setCreateTime(now);
                orderDetail.setBuyerId(userId);
                orderDetail.setItemId(item.getItemId());
                orderDetail.setBuyNum(item.getItemNum());
                orderDetail.setMchtId(itemBaseOutput.getUserId());
                orderDetail.setItemPrice(itemBaseOutput.getSellingPrice());
                orderDetail.setTransPrice(itemBaseOutput.getDiscountPrice());
                orderDetail.setPostage(itemBaseOutput.getPostage());
                orderDetail.setDataStatus(DataStatus.USE.value());
                orderDetail.setOrderPrice(orderDetail.getTransPrice().multiply(new BigDecimal(orderDetail.getBuyNum())));
                orderDetail.setItemName(itemBaseOutput.getItemName());
                orderDetail.setIscomment(0);
                orderDetails.add(orderDetail);
                orderPrice = orderPrice.add(itemBaseOutput.getSellingPrice().multiply(new BigDecimal(orderDetail.getBuyNum())));//计算订单总价
                transPrice = transPrice.add(orderDetail.getTransPrice().multiply(new BigDecimal(orderDetail.getBuyNum())));//计算订单成交总价
                postage = itemBaseOutput.getPostage().compareTo(postage) > 0 ? itemBaseOutput.getPostage() : postage;
                shopCartIds.add(item.getId());
                createSnapshot(orderDetail);//创建商品快照信息
            }
        }
        if (orderDetails.isEmpty()) {
            iOrderAtomSvc.deleteOrderBase(orderBase.getId());//如果商品不存在，删除订单
            return -1;
        }
        iOrderDetailAtomSvc.insertOrderDetails(orderDetails);
        orderBase.setOrderPrice(orderPrice);
        orderBase.setTransPrice(transPrice);
        orderBase.setPostage(postage);
        iOrderAtomSvc.updateOrderBase(orderBase);//更新订单价格信息
        iShopCartAtomSvc.deleteShoppingCart(shopCartIds);//删除购物车商品

        OrderLogInput orderLogInput = new OrderLogInput();
        orderLogInput.setOrderId(orderBase.getId());
        orderLogInput.setBeforProcess(-1);
        orderLogInput.setAfterProcess(OrderState.INIT.value());
        orderLogInput.setBuyerId(orderBase.getBuyerId());
        orderLogInput.setMchtId(orderBase.getMchtId());
        orderLogInput.setComment("创建订单");
        orderLogInput.setCreateTime(DateUtil.newNowDate());
        orderLogInput.setDataStatus(DataStatus.USE.value());
        orderLogInput.setType(OrderLogType.CREATE.value());
        orderLogInput.setState(1);
        iOrderLogAtomSvc.addOrderLog(orderLogInput);
        return orderBase.getId();
    }

    /**
     * @Function com.shop.trade.api.service.impl.OrderSvc.createSnapshot
     * @Description //TODO 创建订单商品快照
     *
     * @param: orderDetail
     * @return java.lang.Integer
     * @errorCode //TODO
     *
     * @Author zhoulk
     * @Date 2019/4/15 10:11
     *
     **/
    private Integer createSnapshot(OrderDetail orderDetail) {
        SnapshotInput snapshotInput = new SnapshotInput();
        ItemDetailsOutput itemDetailsOutput = iItemAtomFeignClientSvc.qryItemDetails(orderDetail.getItemId());
        ItemBaseOutput itemBaseOutput = iItemAtomFeignClientSvc.qryItemBase(orderDetail.getItemId());
        snapshotInput.setOrderId(orderDetail.getOrderId());
//        snapshotInput.setDetailId(orderDetail.getId());
        snapshotInput.setItemId(orderDetail.getItemId());
        snapshotInput.setItemName(itemBaseOutput.getItemName());
        snapshotInput.setItemImgs(itemDetailsOutput.getImgs());
        snapshotInput.setMainImg(itemDetailsOutput.getMainImg());
        snapshotInput.setDetail(itemDetailsOutput.getDetails());
        snapshotInput.setSpec(itemDetailsOutput.getSpecification());
        snapshotInput.setBuyPrice(itemBaseOutput.getBuyPrice());
        snapshotInput.setIntro(itemDetailsOutput.getIntro());
        snapshotInput.setReason(itemDetailsOutput.getReason());
        snapshotInput.setSellingPrice(itemBaseOutput.getSellingPrice());
        snapshotInput.setDiscountPrice(itemBaseOutput.getDiscountPrice());
        snapshotInput.setPostage(itemBaseOutput.getPostage());
        snapshotInput.setItemNew(itemBaseOutput.getItemNew());
        snapshotInput.setCategory(itemBaseOutput.getCategory());
        snapshotInput.setMchtId(itemBaseOutput.getUserId());
        snapshotInput.setCreateTime(DateUtil.newNowDate());
        snapshotInput.setDataStatus(DataStatus.USE.value());
        snapshotInput.setBuyNum(orderDetail.getBuyNum());
        ServiceBean<Integer> serviceBean = iSnapshotAtomSvc.addSnapshot(snapshotInput);
        if (serviceBean.isSuccess()) {
            return serviceBean.getData();
        }
        return -1;
    }

    /**
     * @Function com.shop.trade.api.service.impl.OrderSvc.createPayOrder
     * @Description //TODO 创建支付单
     *
     * @param: orderBaseInput
     * @return java.lang.Integer
     * @errorCode //TODO
     *
     * @Author zhoulk
     * @Date 2019/4/14 1:01
     *
     **/
    private Integer createPayOrder(OrderBase orderBase) {
        if (orderBase.getPayType().intValue() == 1) {
            return -1;
        }
        if (orderBase.getOrderStatus().intValue() != OrderState.INIT.value()) {
            return -1;
        }
        OrderPayInput orderPayInput = new OrderPayInput();
        orderPayInput.setBuyerId(orderBase.getBuyerId());
        orderPayInput.setOrderId(orderBase.getId());
        orderPayInput.setMchtId(orderBase.getMchtId());
        orderPayInput.setPayType(orderBase.getPayType());
        orderPayInput.setPayStatus(PayState.WAIT.value());
        orderPayInput.setPayPrice(orderBase.getPayPrice());
        orderPayInput.setBalance(orderBase.getBalance());
        orderPayInput.setCreateTime(DateUtil.newNowDate());
        orderPayInput.setDataStatus(DataStatus.USE.value());
        orderPayInput.setComment("订单支付");
        ServiceBean<Integer> serviceBean = iPayAtomSvc.insertOrderPay(orderPayInput);
        return serviceBean.isSuccess() ? serviceBean.getData() : -1;
    }

    private boolean refund(OrderBaseOutput orderBaseOutput, Integer mchtId) {
        UserPayOutput userPayOutput = iUserAtomFeignClientSvc.qryUserPayByUserId(orderBaseOutput.getBuyerId());
        BigDecimal afterBalance = userPayOutput.getBalance().add(orderBaseOutput.getPayPrice()).add(orderBaseOutput.getBalance());
        Integer afterIntegral = userPayOutput.getIntegral() - (orderBaseOutput.getPayPrice().add(orderBaseOutput.getBalance()).intValue());
        UserPayLogInput userPayLogInput = new UserPayLogInput();
        userPayLogInput.setUserId(orderBaseOutput.getBuyerId());
        userPayLogInput.setOrderId(orderBaseOutput.getId());
        userPayLogInput.setPayId(1);
        userPayLogInput.setBalance(orderBaseOutput.getPayPrice().add(orderBaseOutput.getBalance()));
        userPayLogInput.setBeforBalance(userPayOutput.getBalance());
        userPayLogInput.setAfterBalance(afterBalance);
        userPayLogInput.setLogType(1);
        userPayLogInput.setModType(1);
        userPayLogInput.setComment("取消订单退款");
        userPayLogInput.setCreateTime(DateUtil.newNowDate());
        userPayLogInput.setDataStatus(DataStatus.USE.value());
        iUserAtomFeignClientSvc.addUserPayLog(userPayLogInput);
        userPayLogInput.setBalance(null);
        userPayLogInput.setBeforBalance(null);
        userPayLogInput.setAfterBalance(null);
        userPayLogInput.setIntegral(orderBaseOutput.getPayPrice().add(orderBaseOutput.getBalance()).intValue());
        userPayLogInput.setBeforIntegral(userPayOutput.getIntegral());
        userPayLogInput.setAfterIntegral(afterIntegral);
        userPayLogInput.setLogType(2);
        userPayLogInput.setModType(2);
        iUserAtomFeignClientSvc.addUserPayLog(userPayLogInput);

        OrderPayInput orderPayInput = new OrderPayInput();
        orderPayInput.setOrderId(-1);
        orderPayInput.setBuyerId(orderBaseOutput.getBuyerId());
        orderPayInput.setMchtId(mchtId);
        orderPayInput.setPayType(PayType.REFUND.value());
        orderPayInput.setPayStatus(1);
        orderPayInput.setComment("取消订单退款");
        orderPayInput.setPayTime(DateUtil.newNowDate());
        orderPayInput.setCreateTime(DateUtil.newNowDate());
        orderPayInput.setDataStatus(DataStatus.USE.value());
        orderPayInput.setBalance(orderBaseOutput.getPayPrice().add(orderBaseOutput.getBalance()));
        iPayAtomSvc.insertOrderPay(orderPayInput);
        UserPayInput userPayInput = new UserPayInput();
        userPayInput.setId(userPayOutput.getId());
        userPayInput.setBalance(afterBalance);
        userPayInput.setModifyTime(DateUtil.newNowDate());
        userPayInput.setIntegral(afterIntegral);//扣减积分
        ServiceBean<String> serviceBean = iUserAtomFeignClientSvc.modUserPay(userPayInput);
        return serviceBean.isSuccess();
    }

    private boolean sendMsg(Integer userId,String content,SmsContent smsContent){
        UserBaseOutput userBaseOutput = iUserAtomFeignClientSvc.qryUserBaseByUserId(userId);
        MessageInput messageInput = new MessageInput();
        messageInput.setSendId(1008612);
        messageInput.setAcceptId(userId);
        messageInput.setAccptPhone(userBaseOutput.getPhone());
        messageInput.setMsgTitle("订单处理");
        messageInput.setMsgContent(content);
        messageInput.setMsgType(1);
        messageInput.setSendTime(DateUtil.newNowDate());
        messageInput.setAccptType(1);
        messageInput.setMsgStatus(0);
        messageInput.setAccptEmail(userBaseOutput.getEmail());
        messageInput.setCreateTime(DateUtil.newNowDate());
        messageInput.setDataState(DataStatus.USE.value());
        messageInput.setAccptTip(smsContent.value());
        iUserAtomFeignClientSvc.sendMsg(messageInput);
        return true;
    }
}
